package org.kfive.nova.design.behavior.interpreter;

import java.util.Stack;

/**
 * Created by admin on 2017-02-20.
 */
public class Calculator {

    private Expression expression;

    public Calculator(String experssion){
        Stack<Expression> expressionStack = new Stack<Expression>();
        char[] chars = experssion.toCharArray();
        Expression left = null;
        Expression right = null;
        for (int i = 0;i<chars.length;i++){
            switch (chars[i]){
                case '+':
                    left = expressionStack.pop();
                    right = new TerminalExpression(String.valueOf(chars[++i]));
                    expressionStack.push(new AddNonterminalExpression(left,right));
                    break;
                case '-':
                    left = expressionStack.pop();
                    right = new TerminalExpression(String.valueOf(chars[++i]));
                    expressionStack.push(new SubNonterminalExpression(left,right));
                    break;
                default:
                    expressionStack.push(new TerminalExpression(String.valueOf(chars[i])));
            }
        }
        this.expression = expressionStack.pop();
    }

    public Object calculate(Context context){
        return this.expression.interpreter(context);
    }
}
